package com.zjw.zy.base.publisher;

import androidx.annotation.NonNull;

import com.zjw.zy.smi.JustWithIt;
import com.zjw.zy.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/10/24 9:04
 */
public abstract class BasePublisher<Observer> implements IPublisher<Observer> {

    private static final String TAG = "BasePublisher";

    private final List<Observer> mObservers = new ArrayList<>();

    @Override
    public final void subscribe(@NonNull Observer observer) {
        synchronized (mObservers) {
            if (mObservers.contains(observer)) {
                return;
            }
            mObservers.add(observer);
        }
    }

    @Override
    public final void unsubscribe(@NonNull Observer observer) {
        synchronized (mObservers) {
            mObservers.remove(observer);
        }
    }
    @Override
    public final void clear() {
        synchronized (mObservers) {
            mObservers.clear();
        }
    }

    @Override
    public final void publish(@NonNull JustWithIt<Observer> call) {
        synchronized (mObservers) {
            requireExecutor().execute(() -> {
                LogUtils.d(TAG, "publish " + call);
                for (Observer mObserver : mObservers) {
                    call.onWith(mObserver);
                }
            });
        }
    }

    @NonNull
    protected abstract Executor requireExecutor();

}
